let canvas = document.querySelector('#myCanvas')
let context = canvas.getContext('2d')

//初始化canvas
function resizeCanvas(){
  canvas.width = window.innerWidth
  canvas.height = window.innerHeight
}
function clearCanvas(){
  context.fillStyle = '#111'
  context.fillRect(0,0,canvas.width,canvas.height)
}
window.addEventListener('resize',resizeCanvas,false)
resizeCanvas()

//开始画图
// let radius = 0 //圆心半径
let particles = []
function mousedownHandler(e){
  let x = e.clientX
  let y = e.clientY
  fire(x,y)
}
document.addEventListener('mousedown',mousedownHandler)

let rid
function fire(x,y){
  createFireWorks(x,y)
  function tick(){
    context.globalCompositeOperation = 'destination-out';
    context.fillStyle = 'rgba(0,0,0,'+25/100+')';
    context.fillRect(0,0,canvas.width,canvas.height);
    context.globalCompositeOperation = 'lighter';
    drawFireWorks()
    rid = requestAnimationFrame(tick);
  }
  cancelAnimationFrame(rid);
  tick()
  // setInterval(tick,30)
}
function createFireWorks(x,y) {
  particles = []
  let hue = Math.floor(Math.random()*51)+150;
  let hueVariance = 30;
  let count = 100; //烟花粒子数量,radius //烟花环绕半径
  for (let i=0;i<count;i++){
    let p = {}
    let angle = Math.floor(Math.random()*360) //烟花粒子角度
    p.x = x
    p.y = y
    p.angle = angle //烟花粒子角度
    p.radians = angle * Math.PI / 180  //烟花例子的弧度
    p.radius = 2
    p.speed = (Math.random()*5) + 0.4
    p.size = Math.floor(Math.random()*3)+1
    p.hue = Math.floor(Math.random()*((hue+hueVariance)-(hue-hueVariance)))+(hue-hueVariance);
    p.brightness = Math.floor(Math.random()*31)+50;
    p.alpha = (Math.floor(Math.random()*61)+40)/100;
    particles.push(p)
  }
}
function drawFireWorks(){
  clearCanvas()
  for(let i=0;i<particles.length;i++){
    let p = particles[i]

    let vx = Math.cos(p.radians) * p.radius;
    let vy = Math.sin(p.radians) * p.radius + 0.4;
    p.x += vx;
    p.y += vy;
    p.radius *= 1 - p.speed/100;
    p.alpha -= 0.005;


    // p.vx = p.x + p.radius * Math.cos(p.radians)
    // p.vy = p.y + p.radius * Math.sin(p.radians)
    // p.radius += p.speed+1
    context.beginPath()
    // context.arc(p.vx,p.vy,p.size,0,Math.PI*2,false)
    context.arc(p.x,p.y,p.size,0,Math.PI*2,false)
    context.closePath()
    context.fillStyle = 'hsla('+p.hue+', 100%, '+p.brightness+'%, '+p.alpha+')';
    context.fill()
  }
}